package com.foodorder.service;

import com.foodorder.entity.Coupon;
import com.foodorder.entity.Product;
import com.foodorder.entity.StoreFollow;
import com.foodorder.entity.User;
import com.foodorder.entity.UserCoupon;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时任务服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ScheduledTaskService {
    
    private final StoreFollowService storeFollowService;
    private final NotificationService notificationService;
    private final CouponService couponService;
    private final ProductService productService;
    private final UserService userService;
    
    /**
     * 每天上午10点推送新品通知
     */
    @Scheduled(cron = "0 0 10 * * ?")
    public void pushDailyNewProducts() {
        log.info("开始执行每日新品推送任务...");
        
        try {
            // 获取所有有关注者的店铺
            List<StoreFollow> allFollows = storeFollowService.getNotificationEnabledFollowers(null);
            
            // 按店铺分组推送
            allFollows.stream()
                    .collect(java.util.stream.Collectors.groupingBy(StoreFollow::getStoreId))
                    .forEach((storeId, follows) -> {
                        // 获取该店铺的新品（假设最近7天内添加的商品为新品）
                        List<Product> newProducts = productService.getRecentProducts(storeId, 7);
                        
                        if (!newProducts.isEmpty()) {
                            String storeName = getStoreName(storeId);
                            Product featuredProduct = newProducts.get(0); // 选择第一个新品作为推荐
                            
                            // 推送给所有关注该店铺的用户
                            notificationService.pushNewProductNotification(
                                    storeId, 
                                    storeName, 
                                    featuredProduct.getName()
                            );
                        }
                    });
            
            log.info("每日新品推送任务完成");
            
        } catch (Exception e) {
            log.error("每日新品推送任务执行失败: {}", e.getMessage());
        }
    }
    
    /**
     * 每天晚上8点推送优惠券到期提醒
     */
    @Scheduled(cron = "0 0 20 * * ?")
    public void pushCouponExpiryReminder() {
        log.info("开始执行优惠券到期提醒任务...");
        
        try {
            // 查找即将过期的优惠券（3天内过期）
            LocalDateTime threeDaysLater = LocalDateTime.now().plusDays(3);
            List<Coupon> expiringCoupons = couponService.findExpiringCoupons(threeDaysLater);
            
            for (Coupon coupon : expiringCoupons) {
                // 获取拥有该优惠券的用户
                List<UserCoupon> userCoupons = 
                        couponService.getUserCouponsForCoupon(coupon.getId());
                
                for (UserCoupon userCoupon : userCoupons) {
                    if (userCoupon.getStatus() == UserCoupon.UseStatus.UNUSED) {
                        User user = userService.findById(userCoupon.getUserId());
                        if (user != null && user.getEmail() != null) {
                            String expiryDate = coupon.getValidTo()
                                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                            
                            notificationService.pushCouponExpiryNotification(
                                    user.getEmail(),
                                    coupon.getName(),
                                    expiryDate
                            );
                        }
                    }
                }
            }
            
            log.info("优惠券到期提醒任务完成");
            
        } catch (Exception e) {
            log.error("优惠券到期提醒任务执行失败: {}", e.getMessage());
        }
    }
    
    /**
     * 每周一上午9点推送周度促销活动
     */
    @Scheduled(cron = "0 0 9 * * MON")
    public void pushWeeklyPromotions() {
        log.info("开始执行周度促销推送任务...");
        
        try {
            // 模拟推送周度促销活动
            String promotionTitle = "周一特惠活动";
            String promotionContent = String.format(
                    "亲爱的用户，\n\n" +
                    "新的一周开始了！本周我们为您准备了丰富的优惠活动：\n\n" +
                    "🎉 周一至周三：全场8.8折\n" +
                    "🎁 周四至周五：买二送一\n" +
                    "💰 周末特惠：满减优惠券大放送\n\n" +
                    "活动时间：%s 至 %s\n\n" +
                    "快来享受美食吧！\n\n" +
                    "美食订餐平台",
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM月dd日")),
                    LocalDateTime.now().plusDays(6).format(DateTimeFormatter.ofPattern("MM月dd日"))
            );
            
            // 推送给所有有关注店铺的用户
            List<StoreFollow> allFollows = storeFollowService.getNotificationEnabledFollowers(null);
            allFollows.stream()
                    .collect(java.util.stream.Collectors.groupingBy(StoreFollow::getStoreId))
                    .forEach((storeId, follows) -> {
                        String storeName = getStoreName(storeId);
                        notificationService.pushPromotionNotification(
                                storeId, 
                                storeName, 
                                promotionTitle, 
                                promotionContent
                        );
                    });
            
            log.info("周度促销推送任务完成");
            
        } catch (Exception e) {
            log.error("周度促销推送任务执行失败: {}", e.getMessage());
        }
    }
    
    /**
     * 每小时检查并处理超时订单
     */
    @Scheduled(fixedRate = 3600000) // 每小时执行一次
    public void processTimeoutOrders() {
        log.info("开始检查超时订单...");
        
        try {
            // 查找超过30分钟未支付的订单
            LocalDateTime timeLimit = LocalDateTime.now().minusMinutes(30);
            // 这里可以添加处理超时订单的逻辑
            
            log.info("超时订单检查完成");
            
        } catch (Exception e) {
            log.error("超时订单检查失败: {}", e.getMessage());
        }
    }
    
    /**
     * 每天凌晨2点清理过期数据
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanupExpiredData() {
        log.info("开始清理过期数据...");
        
        try {
            // 清理过期的优惠券
            // 清理过期的临时数据
            // 更新统计数据
            
            log.info("过期数据清理完成");
            
        } catch (Exception e) {
            log.error("过期数据清理失败: {}", e.getMessage());
        }
    }
    
    // 辅助方法
    private String getStoreName(Long storeId) {
        // 这里应该从数据库获取店铺名称，简化处理
        switch (storeId.intValue()) {
            case 1: return "麦当劳(王府井店)";
            case 2: return "肯德基(三里屯店)";
            case 3: return "海底捞火锅(中关村店)";
            case 4: return "星巴克咖啡(国贸店)";
            case 5: return "必胜客(西单店)";
            default: return "未知店铺";
        }
    }
} 